﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace xycn.framework.midware
{
    /// <summary>
    /// 权限中间件
    /// </summary>
    public static class AuthorizeMiddler
    {
        public static IApplicationBuilder UseXlAuthorize(this IApplicationBuilder app)
        {
            return app.UseMiddleware<BaseAuthMiddlewareExtensions>();
        }
    }
    public class BaseAuthMiddlewareExtensions
    {
        private readonly RequestDelegate _next;
        //public static List<string> filter = new List<string>() { ".js", ".css", ".html", ".png", ".jpg", ".bmp" };

        public BaseAuthMiddlewareExtensions(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 记录请求日志
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (pluginsupport.BaseHelperPlugins.AuthHelper.authHelper != null)
                {
                    #region 权限判断
                    context.Request.EnableBuffering();

                    var routeUrl = context.GetEndpoint().DisplayName.Split(' ')[0];//.Features.Get<IEndpointFeature>()?.Endpoint;

                    var routedic = ControllerManagement.ControllerManager
                                    .controllerInvokers.Where(p => p.IsAuth == false).ToList();
                    bool isauth = true;
                    routedic.ForEach(route =>
                    {
                        if (route.routeAttrs.Count(p =>p.mapRoute == routeUrl) > 0)
                        {
                            isauth = false;
                            context.Items["Auth"] = "AllowAnonymous";
                            return;
                        }
                    });
                    if (isauth)
                    {
                        //context.Request.Form
                        var result = context.Request.Headers.TryGetValue("Authorization", out StringValues authStr);

                        if (string.IsNullOrWhiteSpace(authStr) || !pluginsupport.BaseHelperPlugins.AuthHelper.IsSuccess(authStr))
                        {
                            ResponseError(context, "Unanthorized");
                            return;
                        }
                    }
                    #endregion
                }
                await _next(context);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ResponseError(context, ex.Message);
            }
            await Task.CompletedTask;
        }

        private async void ResponseError(HttpContext context, string errormsg)
        {
            //无授权信息 二次判断 是否404
            var retcode = 401;//默认404

            var novalue_response = new CommonResponse()
            {
                Status = retcode,
                Code = retcode,
                Message = retcode + " " + errormsg,
            };

            var jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(novalue_response);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = retcode;
            await context.Response.BodyWriter.WriteAsync(jsonUtf8Bytes);
            await context.Response.BodyWriter.FlushAsync();
            await context.Response.CompleteAsync();
        }
    }
}
